package com.example.jobback.service.recruiter.impl;

import com.example.jobback.config.AuthConfig;
import com.example.jobback.mapper.PositionMapper;
import com.example.jobback.po.*;
import com.example.jobback.resp.recruiter.deliver.RecruiterCandidateResp;
import com.example.jobback.resp.recruiter.deliver.SeekerResumeResp;
import com.example.jobback.result.Result;
import com.example.jobback.service.common.UserCommonService;
import com.example.jobback.service.recruiter.RecruiterDeliverService;
import com.example.jobback.service.seeker.SeekerCrossService;
import com.example.jobback.util.PhoneNumberUtils;
import com.example.jobback.util.TLUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.example.jobback.util.RedisConstants.RECRUITER_KEY;
import static com.example.jobback.util.RedisConstants.RECRUITER_TTL;

/**
 * @ClassName: RecruiterDeliverServiceImpl
 * @Description:招聘者-投递服务接口实现类
 * @Author: lhb
 * @Date: 2025/7/17
 */
@Service
public class RecruiterDeliverServiceImpl implements RecruiterDeliverService {

    private final SeekerCrossService seekerCrossService;

    private final PhoneNumberUtils phoneNumberUtils;

    private final PositionMapper positionMapper;

    private final AuthConfig authConfig;

    private final UserCommonService userCommonService;

    public RecruiterDeliverServiceImpl(SeekerCrossService seekerCrossService, PositionMapper positionMapper, UserCommonService userCommonService, PhoneNumberUtils phoneNumberUtils, AuthConfig authConfig) {
        this.seekerCrossService = seekerCrossService;
        this.positionMapper = positionMapper;
        this.userCommonService = userCommonService;
        this.phoneNumberUtils = phoneNumberUtils;
        this.authConfig = authConfig;
    }

    /**
     * @Description: 获取已投递 
     * @return Result<List<RecruiterGetDeliverResp>>
     * @Author lhb
     * @CreateTime 2025/7/17 12:02
     */
    @Override
    public Result<List<RecruiterCandidateResp>> getDeliverList() {
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        List<RecruiterCandidateResp> respList = getCandidateList(recruiter, false);
        return Result.success(respList);
    }

    /**
     * @Description:  获取已面试
     * @return Result<List<RecruiterCandidateResp>>
     * @Author lhb
     * @CreateTime 2025/7/17 15:42
     */
    @Override
    public Result<List<RecruiterCandidateResp>> getInterviewList() {
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        List<RecruiterCandidateResp> respList = getCandidateList(recruiter, true);
        return Result.success(respList);
    }

    /**
     * @Description: 邀约面试
     * @param id
     * @return Result<Object>
     * @Author lhb
     * @CreateTime 2025/7/17 16:09
     */
    @Override
    public Result<Object> interview(Long id) {
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        Long recruiterUserId = recruiter.getUserId();
        if(seekerCrossService.interview(id, recruiterUserId) == 0) {
            throw new RuntimeException("操作失败");
        }
        String token=userCommonService.updateRedisUserToken(recruiter.getUserId(),RECRUITER_KEY,authConfig.getJwtRecruiterSecret(),RECRUITER_TTL, TimeUnit.DAYS);
        if(token==null) throw new RuntimeException("token生成失败");
        return Result.success(token);
    }

    /**
     * @Description: 根据UserId查看求职者简历
     * @param userId
     * @return Result<SeekerResumeResp>
     * @Author lhb
     * @CreateTime 2025/7/25 15:13
     */
    @Override
    public Result<SeekerResumeResp> getSeekerResume(Long userId) {
        Recruiter recruiter = TLUtil.get(TLUtil.R);
        Long recruiterUserId = recruiter.getUserId();
        Deliver deliver = seekerCrossService.getDeliverByBothUserId(recruiterUserId, userId);
        if(Objects.isNull(deliver)) {
            throw new NullPointerException("用户未投递");
        }
        SeekerResumeResp resp = seekerCrossService.getSeekerResume(userId);
        if(Objects.isNull(resp)) {
            throw new NullPointerException("用户简历查询异常，为空");
        }
        return Result.success(resp);
    }


    private List<RecruiterCandidateResp> getCandidateList(Recruiter recruiter, Boolean interview) {
        List<RecruiterCandidateResp> respList = new ArrayList<>();
        Long recruiterUserId = recruiter.getUserId();
        List<Deliver> deliverList = seekerCrossService.getDeliversByRecruiterUserId(recruiterUserId, interview);
        if(deliverList.isEmpty()) {
            return respList;
        }
        List<Long> seekerUserIdList = deliverList.stream()
                .map(Deliver::getSeekerUserId)
                .filter(Objects::nonNull)
                .toList();
        List<Long> positionIdList = deliverList.stream()
                .map(Deliver::getPositionId)
                .filter(Objects::nonNull)
                .toList();
        List<Position> positions =positionMapper.getPositionByIds(positionIdList);
        List<User> users = userCommonService.getUsersByUserIds(seekerUserIdList);
        List<Seeker> seekers = seekerCrossService.getSeekersByUserIds(seekerUserIdList);
        //构建map
        Map<Long, User> userMap = users.stream()
                .collect(Collectors.toMap(User::getUserId, elem -> elem));
        Map<Long, Position> positionMap = positions.stream()
                .collect(Collectors.toMap(Position::getPositionId, elem -> elem));
        Map<Long, Seeker> seekerMap = seekers.stream()
                .collect(Collectors.toMap(Seeker::getUserId, elem -> elem));
        for (Deliver deliver : deliverList) {
            RecruiterCandidateResp resp = new RecruiterCandidateResp();
            User user = userMap.get(deliver.getSeekerUserId());
            Seeker seeker = seekerMap.get(deliver.getSeekerUserId());
            Position position = positionMap.get(deliver.getPositionId());
            BeanUtils.copyProperties(seeker, resp);
            BeanUtils.copyProperties(deliver, resp);
            BeanUtils.copyProperties(user, resp);
            resp.setPositionName(position.getPositionName());
            resp.setEndAt(position.getEndAt());
            String phone = "";
            try {
                phone = phoneNumberUtils.decryptPhone(user.getPhoneAes());
                phone = PhoneNumberUtils.maskPhoneNumber(phone);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            resp.setPhone(phone);
            respList.add(resp);
        }
        return respList;
    }
}
